//
//  FriendsGameViewController.m
//  CandyCrushClone
//
//  Created by Petar on 2/26/15.
//  Copyright (c) 2015 Nestorov Engineering. All rights reserved.
//

#import "FriendsGameViewController.h"
#import "FriendGameCell.h"
#import "CommunicationManager.h"

static NSString * const FriendGameCellIdentifier = @"FriendGameCell";

@interface FriendsGameViewController () <FriendGameCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIImageView *myImageView;
@property (weak, nonatomic) IBOutlet UILabel *myNameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *otherPlayerImageView;
@property (weak, nonatomic) IBOutlet UILabel *otherPlayerNameLabel;

@end

@implementation FriendsGameViewController
{
    
    NSArray *_buddyList;
    CommunicationManager *_communicationManager;
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    UINib *cellNib = [UINib nibWithNibName:FriendGameCellIdentifier bundle:nil];
    [_tableView registerNib:cellNib forCellReuseIdentifier:FriendGameCellIdentifier];
    
    _communicationManager = [CommunicationManager sharedManager];
    
    _buddyList = [_communicationManager getBuddyList];
    
    // store my username for later usage
    _myNameLabel.text = [_communicationManager getMyUsername];

}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_buddyList count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    FriendGameCell *cell = [tableView dequeueReusableCellWithIdentifier:FriendGameCellIdentifier forIndexPath:indexPath];
    
    SFSBuddy *buddy = _buddyList[indexPath.row];
    
    [cell configureWithName:buddy.name isOnline:buddy.isOnline forIndexPath:indexPath];
    cell.delegate = self;
    
    return cell;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SFSBuddy *buddy = _buddyList[indexPath.row];
    [self configureViewsForSelectedBuddy:buddy];
    
}


// TODO: Show BuddyVariables on screen ( name, image of his pet and other statistics )
- (void)configureViewsForSelectedBuddy:(SFSBuddy *)buddy
{
    
    _otherPlayerNameLabel.text = buddy.name;
    
}


#pragma mark - FriendGameCell Delegate method
- (void)didPressInviteButtonAtIndexPath:(NSIndexPath *)indexPath
{
    
    SFSBuddy *buddy = _buddyList[indexPath.row];
    [self configureViewsForSelectedBuddy:buddy];
    
    // Send Game Invitation
    [_communicationManager inviteBuddyToPlayGame:buddy.name];
    
}


- (IBAction)didPressBackButton:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (BOOL)prefersStatusBarHidden
{
    return YES;
}


@end
